package job.work.config.filter;


import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import job.work.domain.response.AuthCode;
import job.work.domain.response.CommonCode;
import job.work.domain.response.ResponseResult;
import job.work.domain.system.entity.pojo.dto.AuthToken;
import job.work.domain.system.entity.pojo.model.SystemUser;
import job.work.framework.ExceptionCast;
import job.work.utils.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by echisan on 2018/6/23
 */
@Slf4j
public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    /**
     * 认证管理器
     */
    private AuthenticationManager authenticationManager;

    public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
        // 过滤的地址, 暂时只针对此地址过滤
        super.setFilterProcessesUrl("/userlogin");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try {
            SystemUser loginUser = new ObjectMapper().readValue(request.getInputStream(), SystemUser.class);
            // 使用认证管理器去认证
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword(), new ArrayList<>()));
        } catch (IOException e) {
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @param request
     * @param response
     * @param chain
     * @param authResult
     * @throws IOException
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest request,
                                            HttpServletResponse response,
                                            FilterChain chain,
                                            Authentication authResult) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        SystemUser jwtUser = (SystemUser) authResult.getPrincipal();
        ObjectMapper objectMapper = new ObjectMapper();
        if ("1".equals(jwtUser.getStatus())) {
            String rRString = JSON.toJSONString(new ResponseResult<>(AuthCode.AUTH_LOGIN_TOKEN_DISABLE));
            String responseMessage = (String) JSON.parse(objectMapper.writeValueAsString(rRString));
            response.getWriter().write(responseMessage);
            return;
        }
        log.info("jwtUser----->:{}", jwtUser.toString());
        AuthToken tokenUser = JwtTokenUtils.createTokenUser(jwtUser);

        //TODO 把token 保存到Redis中
        String rRString = JSON.toJSONString(new ResponseResult<>(CommonCode.SUCCESS, tokenUser));
        //转化为json格式
        String responseMessage = (String) JSON.parse(objectMapper.writeValueAsString(rRString));
        response.getWriter().write(responseMessage);
    }

    /**
     * 这是验证失败时候调用的方法
     * @param request
     * @param response
     * @param failed
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        String rRString = null;
        ObjectMapper objectMapper = new ObjectMapper();
        AuthCode attribute = (AuthCode) request.getAttribute("10010");
        if(attribute == null){
            rRString = JSON.toJSONString(new ResponseResult<>(AuthCode.AUTH_CREDENTIAL_ERROR));
        }else{
            rRString = JSON.toJSONString(new ResponseResult<>(attribute));
        }

        String responseMessage = (String) JSON.parse(objectMapper.writeValueAsString(rRString));
        response.getWriter().write(responseMessage);
    }


}
